// 下拉菜单控制逻辑
let inMenu = false;

function showDropdown() {    
    document.getElementById('userDropdown').classList.add('show');
}

function hideDropdown() {
    if(inMenu){
        return;
    }
    
    document.getElementById('userDropdown').classList.remove('show');
}

function leaveMenu(){
    inMenu =false;
    hideDropdown();
}
// 退出登录示例函数
function logout() {    
    LoginOut();   
}

function permissionEdit(){
    window.location.href = 'permission';
}


async function GetUsrInfo() {
    try {
        // 获取认证信息（根据实际存储方式调整）
        const token = localStorage.getItem('authToken');
        if (!token) AuthReDirection(false);

        const response = await fetch(`/api/employee/info`, {
            method: 'GET',
            headers: new Headers({
                'Authorization': `${token}`
            }),
        });
        if (!response.ok) {
            if (response.status == 401) {
                AuthReDirection(false);
            }
            else if(response.status == 402){
                const data = await response.json();
                AuthPermissionErr(data.error);
                return
            }
            else {
                throw new Error('数据加载失败')
            }
        }

        const responseJs = await response.json();
        if(responseJs.code == '0'){
            const data = await responseJs.data
            return data;
        }else{
            //alert("获取用户信息失败:" + response.message)
            console.log("获取用户信息失败:" + response.message)
            return '';
        }

    }
    catch(err){
        alert(err)
    }
}



// 保持菜单打开当鼠标在菜单上时
document.getElementById('userDropdown').addEventListener('mouseover', () => {
    console.log("mouse in menu");
    inMenu = true;    
});

document.getElementById('userDropdown').addEventListener('mouseout', leaveMenu);


document.addEventListener('DOMContentLoaded', async () => {    
    const data = await GetUsrInfo();
    if(data){
        const acount = data.Account
        const name = data.Name
        const company =data.Company
        const department = data.Department



        const userAvatar = document.querySelector('.user-avatar')
        const userName = document.querySelector('.user-name')


        if(name == 'empty' || name == ''){            
            userName.textContent = acount;
            userAvatar.textContent = '';
        }else{
            userName.textContent = name;
            userAvatar.textContent = name.charAt(0);
        }
    }
    
});